<?php

class CCouponCode extends Zend_Db_Table
{
	protected $_name;
	protected $_primary;

	public function __construct()
	{
		$this->_name = R_PRE."couponcode";
		$this->_primary = "code";
		parent::__construct();
	}
	
	public function createcode($data)
	{
		$couponcodeid = $this->insert($data);
		return $couponcodeid;
	}
	
	public function isexist($code)
	{
		$db=$this->getAdapter();
		$where = $db->quoteInto('code = ?', $code);
		return $this->fetchRow($where);
	}
	
	public function codelist($from, $counts, $where='')
	{
		$db=$this->getAdapter();

        $itemTable=$this->_name;

        $select = $db->select();
        $select->from($itemTable,'*');

        if($where!='')
        {
            $select->where($where);
        }

        if($counts!=0)
        {

            $select->limit($counts, $from);

        }
        
        $select->order('createtime desc');
        return $db->fetchAll($select);
	}
	
	public function codedelete($code)
	{
		$db=$this->getAdapter();
		$where = $db->quoteInto('code = ?', $code);
		return $this->delete($where);
	}

	public function codeproduct()
	{
		
	}
	
	public function getAllItemCounts($where = '')
	{
		$db=$this->getAdapter();

        $select = $db->select();

        $select->from($this->_name);

        if($where!='')
        {
            $select->where($where);
        }

        return count($db->fetchAll($select));
	}
	
	public function getAllcodes()
	{
		$db=$this->getAdapter();

        $itemTable=$this->_name;

        $select = $db->select();
        $select->from($itemTable,'*');
		return $db->fetchAll($select);
	}
	
	public function editcode($code, $data)
	{
		$db=$this->getAdapter();
		
		$where = $db->quoteInto('code = ?', $code);
		
		$rows_affected=$db->update($this->_name,$data,$where);
		
		if($rows_affected!=1){
			
			return false;
			
		}else{
			
			return true;
			
		}
	}
	
	public function isexpires($code)
	{
		$db=$this->getAdapter();
		$where = $db->quoteInto('code = ?', $code);
		$data = $this->fetchRow($where);
		if(time() > $data->endtime)
			return true;
		return false;
	}
	
	public function productdel($itemarray)
	{
		if(empty($itemarray))
			return true;
		$codes = $this->getAllcodes();
		foreach ($codes as $cv) {
			$editdata = array(
				'itemids' => join(',', array_diff(split(',',$cv['itemids']),$itemarray))
			);
			$this->editcode($cv['code'], $editdata);
		}
		return true;
	}
}